<?php
// +----------------------------------------------------------------------
// | QbtCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.qbt8.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 千佰特 <http://www.qbt8.com>
// +----------------------------------------------------------------------
namespace plugins\qbt_db_backup\controller;

use cmf\controller\PluginAdminBaseController;
use think\Db;

class AdminIndexController extends PluginAdminBaseController
{

    public function _initialize()
    {
        $adminId = cmf_get_current_admin_id();//获取后台管理员id，可判断是否登录
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        } else {
            $this->error('未登录');
        }
    }

    /**
     * 数据备份
     * @adminMenu(
     *     'name'   => '数据备份',
     *     'parent' => 'portal/AdminConfig/#',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '数据备份',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $list = Db::query("SHOW TABLE STATUS");
        $list  = array_map('array_change_key_case', $list);
        foreach ($list as $k => $v){
            if ($v['name'] === 'ysk_backup' || $v['name'] === 'ysk_plugin'){
                unset($list[$k]);
            }
        }
        $this->assign("list", $list);
        return $this->fetch('/admin_index');
    }

    //备份记录列表
    public function list1(){
        $lists = Db::table('ysk_backup')->select();
        $this->assign("list", $lists);
        return $this->fetch('/list');
    }

    //备份数据表列表
    public function lists(){
        $dir = 'db'.$this->request->param('dir');
        $list = Db::query("SHOW TABLE STATUS");
        $list  = array_map('array_change_key_case', $list);
        $lists=[];
        foreach ($list as $k=>$v){
            if(is_file(CMF_ROOT_DB.'data/'.$dir.'/'.$v['name'].'.sql')){
                $lists[$k]['name'] = $v['name'];
                $lists[$k]['time'] = date("Y-m-d H:i:s",filemtime(CMF_ROOT_DB.'data/'.$dir.'/'.$v['name'].'.sql'));
            }
        }
        $this->assign("dir", $dir);
        $this->assign("list", $lists);
        return $this->fetch('/lists');
    }

    /**
     * 备份数据库
     */
    public function backup(){
        $list = $_GET['str'];
        $time = $_GET['time'];
        $dir = date("YmdHis",$time);
        //dump(CMF_ROOT_DB);return;
        if(!is_dir(CMF_ROOT_DB.'data/db'.$dir)){
            mkdir('data/db'.$dir, 0777, true);
        }
        $myfile1 = fopen(CMF_ROOT_DB."data/db$dir/".$dir.".sql", "a") or die("Unable to open file!");
        $str = $this->backup_table($list);
        $this->save_file($list.'.sql',$str,'db'.$dir);
        $str = str_replace("*****","\r",$str);
        fwrite($myfile1, $str);
        fclose($myfile1);
        echo $time;
    }

    /**
     * 备份数据库记录
     */
    public function backup1(){
        $count = $_GET['count'];
        $time = $_GET['time'];
        $data['create_time'] = $time;
        $data['table_num'] = $count;
        $id =  Db::name('backup')->insert($data);
        if ($id){
            echo 1;
        }else{
            echo -1;
        }
    }

    /**
     * 备份数还原
     */
    public function restore(){
        $str = $_GET['str'];
        $dir = $_GET['dir'];
        $str = $this->get_file($dir.'/'.$str.'.sql');
        $arr = explode(';*****',rtrim($str,';*****'));
        foreach ($arr as $k1=>$v1){
            Db::execute($v1);
        }
        echo 1;
    }

    /**
     * 优化表
     */
    public function optimize(){
        $tables = $_GET['str'];
        if(is_array($tables)){
            $tables = implode('`,`', $tables);
            $result = Db::query("OPTIMIZE TABLE `{$tables}`");
            if ($result){
                echo 1;
            }else{
                echo -1;
            }
        } else{
            $result = Db::query("OPTIMIZE TABLE `{$tables}`");
            if ($result){
                echo 1;
            }else{
                echo -1;
            }
        }
    }

    /**
     * 修复表
     */
    public function repair(){
        $tables = $_GET['str'];
        if(is_array($tables)){
            $tables = implode('`,`', $tables);
            $result = Db::query("REPAIR TABLE `{$tables}`");
            if ($result){
                echo 1;
            }else{
                echo -1;
            }
        }else{
            $result = Db::query("REPAIR TABLE `{$tables}`");
            if ($result){
                echo 1;
            }else{
                echo -1;
            }
        }
    }

    public function backup_table($table){
        $info = Db::query("show create table $table");
        $str = "DROP TABLE IF EXISTS `$table`;*****";
        $str .= $info[0]['Create Table'].';*****';
        $list = Db::table($table)->select();
        foreach ($list as $k=>$v){
            $values = implode(',',array_values($v));
            $values = str_replace(',',"','",$values);
            $str.="INSERT INTO `$table` VALUES ('".$values."');*****";
        }
        return $str;
    }

    //保存文件
    public function save_file($filename,$str,$dir){
        $myfile = fopen(CMF_ROOT_DB."data/$dir/".$filename, "w") or die("Unable to open file!");
        fwrite($myfile, $str);
        fclose($myfile);
    }

    //读取文件
    public function get_file($filename){
        $myfile = fopen(CMF_ROOT_DB."data/".$filename, "r") or die("Unable to open file!");
        $str = fread($myfile,filesize(CMF_ROOT_DB."data/".$filename));
        fclose($myfile);
        return $str;
    }

    //删除
    public function del(){
        $id = $this->request->param('id', 0, 'intval');
        $info = Db::name('backup')->where(['id'=>$id])->find();
        $dir = CMF_ROOT_DB."data/db".date("YmdHis",$info['create_time']);
        $result =  Db::name('backup')->where(['id'=>$id])->delete();
        if ($result){
            array_map('unlink', glob($dir."/*.*"));
            rmdir($dir);
            $this->success('删除成功');
        }else{
            $this->error('删除成功');
        }
    }
}
